import { observable, action, toJS } from 'mobx';
import { Toast, Tools, Bubble, Modal } from 'weaver-mobile';
import { Form } from 'weaver-mobile-page';
import * as Api from '../../api/CommunicationApi';
const getLabel = Tools.getLabel;

const markArr = () => [
  {key: 'unread', name: getLabel(25420, '标记为未读')},
  {key: 'read', name: getLabel(18492, '标记为已读')},
  {key: 'important', name: getLabel(382626, '标星')},
  {key: 'normal', name: getLabel(382669, '取消标星')},
  {key: 'hidden', name: getLabel(16636, '隐藏')},
  {key: 'show', name: getLabel(25424, '取消隐藏')},
];

const initalState = {
  page: '',
  labelManageList: [],
  manageSaveLoading: false,
  createSaveLoading: false,
}

export default class TagStore {
  markArr = markArr();
  @observable page = initalState.page;
  @observable tagLoading = true;
  @observable coworkids = null;  // 进入当前页面的协作id

  @observable labelList = []; // 标签列表
  @observable labelManageList = []; //标签管理列表
  @observable check = 0; // 标签的选择数量
  @observable labelType = {}; // 标签选择
  @observable type = {}; // 标记为类型key值
  @observable typeCheck = false;
  @observable tempList = []; // 所有标签列表，保存标签时的传参工作

  @observable tagForm = new Form.Store({ route: '/communication/tag', id:'createTag' });
  @observable newTagLoading = true;
  @observable labelOrder = '0';
  @observable params = {  // 保存标签所用参数
    operateType: '',  // 操作类型，新建，编辑，删除（add;edit;delete）
    id: '', // 标签ID
    labelName: '',  // 标签名称
    labelColor: '', // 标签颜色
    isUsed: '', // 启用
    labelOrder: '', // 取所有标签里面最大的labelOrder值+1
    textColor: '',  // 文本颜色 无
    labelType: '',  // 标签类型（自定义:label;版块:typePlate）
    typeid: '', // 唯独版块标签才有
  }

  @observable manageSaveLoading = initalState.manageSaveLoading; // 标签管理保存Loading
  @observable createSaveLoading = initalState.createSaveLoading; // 新建 || 编辑 Tag保存Loading

  @action setStoreState = (params) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    })
  }

  @action('请求标签列表')
  getCoworkLabelList = () => {
    this.tagLoading = true;
    this.labelList = [];
    Api.getCoworkLabelList().then(
      action("fetchSuccess", res => {
        let max = res.labelList && res.labelList[0] && res.labelList[0].labelOrder || 1;
        res.labelList && res.labelList.map((item) => {
          if (item.labelType === 'label') {
            this.labelList.push(item)
          }
          if (item.labelOrder * 1 > max) {
            max = item.labelOrder * 1;
          }
          this.labelOrder = max * 1 + 1;
          return item;
        })
        this.tagLoading = false;
      })
    )
  }

  @action('标记为操作')
  tagMark = (callback) => {
    let tagType = '';
    let templableType = [];
    Object.keys(toJS(this.type)).forEach(item => {
      tagType = item;
    })
    Object.keys(toJS(this.labelType)).forEach(item => {
      if (toJS(this.labelType)[item] !== false) {
        templableType.push(item);
      }
    })
    if (toJS(templableType).length === 0 && (JSON.stringify(toJS(this.type)) === '{}' || this.type === "")) {
      Toast.info(getLabel(390694, '请执行正确操作！'), 1);
    } else {
      let typeWaring = false, labelTypeWaring = false;
      return new Promise((resovle) => {
        if (JSON.stringify(toJS(this.type)) !== '{}') {
          let tagParams = {
            coworkids: this.coworkids,
            type: tagType
          }
          Api.coworkMarkItemAsType(tagParams).then(res => {
            typeWaring = res.api_status
          })
        }
        if (templableType.length !== 0) {
          let labelParams = {
            coworkids: this.coworkids,
            type: 'addLabel',
            labelIds: templableType.join(',')
          }
          Api.coworkMarkItemAsType(labelParams).then(res => {
            labelTypeWaring = res.api_status
          })
        }
        let timer = setInterval(() => {
          if (labelTypeWaring || typeWaring) {
            Toast.success(getLabel(30700, '操作成功')+'!',1);
            if (callback) callback();
            resovle(true);
            clearInterval(timer);
          }
        },100)
      })
    }
  }

  @action cancelMark = (callback) => {
    let labelParams = {
      coworkids: this.coworkids,
      type: 'deleteAll',
    }
    Api.coworkMarkItemAsType(labelParams);
    if(callback) callback();
  }

  /* ======================================== 新建标签 ======================================== */
  @action
  coworkLabelCondition = (params={}, pathname) => {
    this.newTagLoading = true;
    Api.coworkLabelCondition(params).then(res => {
      this.tagForm.initForm(res.conditioninfo,pathname)
      this.newTagLoading = false;
    })
  }

  @action('保存设置')
  submitTag = (val = {}, callback) => {
    let formParams = this.tagForm.formParams;
    let validResult = this.tagForm.doValidate();
    let tempParams = {  // 参数转换===暂时处理
      ...formParams,
      labelOrder: this.labelOrder
    }
    if (validResult.pass) {
      Object.assign(this.params, val, tempParams);
      this.createSaveLoading = true
      Api.uploadCoworkLabelByMobile(this.params).then(
        action("fetchSuccess", res => {
          if (res.flag) {
            this.labelList = [];
            this.getCoworkLabelList();
            this.getManageLabelList();
            Bubble.success(getLabel(30700, '操作成功')+'!', 1)
            this.tagForm.resetFields();
          }
          this.createSaveLoading = false
          if (callback) callback();
        })
      )
    }else {
      Bubble.error(validResult.message);
    }
  }

  /* ======================================== 标签管理 ======================================== */
  // 获取标签列表
  @action
  getManageLabelList = () => {
    this.tagLoading = true;
    this.labelManageList = [];
    Api.getCoworkLabelList().then(
      action("fetchSuccess", res => {
        this.tempList = res.labelList;
        res.labelList && res.labelList.map((item) => {
          if (item.labelType === 'label') {
            this.labelManageList.push(item)
          }
          this.tagLoading = false;
        })
      })
    )
  }

  @action('删除标签')
  deleteTag = (v, callback) => {
    Modal.alert(getLabel('15097', '确定要删除吗？'), '', [
      { text: getLabel(201, '取消') },
      { text: getLabel(826,"确定"), 
        onPress: () => {
          this.labelManageList = this.labelManageList.filter(item => item.id !== v) // 前台的响应--视觉效果
          this.tempList.map((item, index) => {  // 修改临时列表，为传参做准备
            if (item.id === v) {
              this.tempList.splice(index, 1);
            }
            return item;
          })
          let params = {
            operateType: 'delete',
            id: v
          }
          Api.uploadCoworkLabelByMobile(params).then(
            action("fetchSuccess", res => {
              if (res.flag) {
                Bubble.success(getLabel(30700, '操作成功')+'!', 1)
                if (callback && typeof callback === 'function') callback() 
              }
            })
          )
        }
      },
    ])
  }

  @action('保存操作')
  saveTag = async (callback) => {
    let params = {
      labelArray: JSON.stringify(toJS(this.tempList))
    }
    this.manageSaveLoading = true;
    Api.uploadCoworkLabelList(params).then(
      action("fetchSuccess", res => {
        if (res.status === '1') {
          Bubble.success(getLabel(30700, '操作成功')+'!', 1)
          this.getCoworkLabelList();
        } else {
          Bubble.error(getLabel(30651, '操作失败')+'!', 1)
        }
        this.manageSaveLoading = false;
        if (callback) callback();
      })
    )
  }

  clear = () => {
    this.setStoreState(initalState);
    this.labelList = [];
    this.check = 0;
    this.labelType = {};
    this.type = '';
    this.labelOrder = '';
    this.params = {
      operateType: '',
      id: '',
      labelName: '',
      labelColor: '',
      isUsed: '',
      labelOrder: '',
      textColor: '',
      labelType: '',
      typeid: '',
    }
  }
}